package com.tt.ProxyFactory.jdk;

import com.tt.TransactionController.TransactionController;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkTransactionProxy implements InvocationHandler {

    private final Object target;
    private final TransactionController transactionController;

    public JdkTransactionProxy(Object target, TransactionController transactionController) {
        this.target = target;
        this.transactionController = transactionController;
    }

    public Object getProxyInstance() {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        try {
            transactionController.beginTransaction();
            result = method.invoke(target, args);
            transactionController.commit();
        } catch (Exception e) {
            transactionController.rollback();
            throw e;
        }
        return result;
    }
}
